package com.situ.stmall.admin.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.stmall.admin.entity.Goods;
import com.situ.stmall.admin.mapper.GoodsMapper;
import com.situ.stmall.admin.mapper.GoodsPicturreMapper;
import com.situ.stmall.admin.service.GoodsService;

@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private GoodsMapper goodsMapper;
	
	@Autowired
	private GoodsPicturreMapper goodsPictureMapper;
	
	@Override
	@Transactional
	public Goods add(Goods goods) {
		goodsMapper.insert(goods);
		
		//批量添加图片操作
		if (goods.getPictures() != null && goods.getPictures().size() > 0) {
			goodsPictureMapper.batchInsert(goods.getId(),goods.getPictures());
		}				
		return goodsMapper.selectByPrimaryKey(goods.getId());
	}

	@Override
	@Transactional
	public Goods edit(Goods goods) {
		// 保存商品信息
		goodsMapper.updateByPrimaryKey(goods);
		
		//保存图片
		//删除原有图片
		goodsPictureMapper.deleteByGoodsId(goods.getId());
		
		
		//添加新图片
		if (goods.getPictures() != null && goods.getPictures().size() > 0) {
			goodsPictureMapper.batchInsert(goods.getId(),goods.getPictures());
		}
		
		return goodsMapper.selectByPrimaryKey(goods.getId());
	}

	@Override
	public Goods remove(Integer id) {
		Goods goods = goodsMapper.selectByPrimaryKey(id);
		if (goods.getStatus() == 0) {
			goods.setStatus(1);
		} else if(goods.getStatus() == 1) {
			goods.setStatus(0);
		}
		goodsMapper.updateByPrimaryKey(goods);
		return goods;
	}

	@Override
	public PageInfo getByPage(Integer page, Integer limit, Goods goods) {
		if (page == null) {
			page = 1;
		}
		if (limit == null) {
			List list = goodsMapper.select(goods);
			limit = list.size();
		}
		
		PageHelper.startPage(page, limit);
		List list = goodsMapper.select(goods);
		PageInfo pageInfo = new PageInfo<>(list);
		return pageInfo;
	}
	
	
	
	

}
